$(document).ready(function(){
	var token = $.zui.store.get("token");
	var userId = $.zui.store.get("userId");
	var currentPage = 1;
	var pageSize = 10;
	console.log('token='+token+",userId="+userId);
	var queryListFun = function(){
		var queryLeftMenuUrl = adminQueryUrl + orgService + queryPageListMethod;
		var param = "";	
		if($("#OrgCode").val()!=''){
			param += "&OrgCode="+$("#OrgCode").val();
		}
		if($("#OrgNameLike").val()!=''){
			param += "&OrgNameLike="+$("#OrgNameLike").val();
		}
		param += "&pageSize="+pageSize;
		param += "&currentPage="+(currentPage-1);
		console.log($("#queryOrgNameLike").val());
		$.ajax({
			url:queryLeftMenuUrl,
			type:'post',
			beforeSend:function(xhr){
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{"token":token,"userId":userId},
			data:param,
			dataType:"JSON",
			success:function(result){
				console.log(result.success);
				if(result.success=='1'){
					//$('#listPager').empty();
					//$('#listPager').data('zui.datagrid',null);
					$('#orgListDataGrid').empty();
					$('#orgListDataGrid').data('zui.datagrid',null);
					
					console.log(result);
					$('#orgListDataGrid').datagrid({
						checkable:true,
						checkByClickRow:true,
					    dataSource: {
					        cols:[
					              {name: 'Org_Code', label: '机构编号', width: 132},
					              {name: 'Org_Name', label: '机构名称', width: 134},
					              {name: 'parentName', label: '上级机构', width: 109},
					              {name: 'Status', label: '机构状态', width: 109},
					              {name: 'Area_Code', label: '机构所属地区', width: 109},
					              {name: 'Contactor', label: '机构联系人', width: 109},
					              {name: 'Mobile', label: '机构联系电话', width: 109},
					              {name: 'Address', label: '机构地址', width: 109},
					        ],
					        array:result.orgListDataGrid
					    }				
					});
					console.log(currentPage);
					console.log(pageSize);
					console.log(result.pageTotal);									
					$('#listPager').pager({
					    page: currentPage,
					    recPerPage:pageSize,
					    elements:['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text','size_menu','goto'],
					    pageSizeOptions:[5,10,20,30,50,100],
					    recTotal: result.pageTotal
					});					
				}else {
					new $.zui.Messager(result.msg, {
					    type: 'warning', // 定义颜色主题
					    placement: 'center' // 定义显示位置
					}).show();
				}
			},
			error:function(result){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning', // 定义颜色主题
				    placement: 'center' // 定义显示位置
				}).show();
			}
		});		
	}
	queryListFun();
	//查询
	$("#searchBtn").click(function(){
		queryListFun();
	});
	
	$('#listPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		pageSize = state.recPerPage;
		queryListFun();
	});	
	
	//添加页面预加载
	$("#addBtn").click(function(){
		$("#addForm")[0].reset();
		var queryParentOrgUrl = adminQueryUrl + orgService + initAddMethod;
		var param = '';	
		$.ajax({
				url:queryParentOrgUrl,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$.each(data.orgParentList, function(i, item){     
							$("#addOrgParentCode").append("<option value='"+item.Org_Code+"'>"+item.Org_Name+"</option>");
						});  
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}			
		});
	});
	//添加菜单保存
	$("#addSaveBtn").click(function(){			
			var validOrgCodeUrl = adminQueryUrl + orgService + validOrgCode;
			var validOrgNameUrl = adminQueryUrl + orgService + validOrgName;
			$("#addForm").validate({
				rules:{
					addOrgCode:{
						"required":true,
						"remote":{
							url:validOrgCodeUrl,
							type:'post',
							dataType:'json',
							beforeSend:function(xhr){//设置请求头信息
								xhr.setRequestHeader("token",token);
								xhr.setRequestHeader("userId",userId);
							},
							headers:{'token':token,'userId':userId},
							data:{
								'orgCode':function(){
									return $("#addOrgCode").val();
								}
							}
						}
					},
					addOrgName:{
						"required":true,
					    "remote":{
							url:validOrgNameUrl,
							type:'post',
							beforeSend:function(xhr){//设置请求头信息
								xhr.setRequestHeader("token",token);
								xhr.setRequestHeader("userId",userId);
							},
							headers:{'token':token,'userId':userId},
							dataType:'json',
							data:{
								'orgName':function(){
									return $("#addOrgName").val();
								},
								'orgParentCode':function(){
									return $("#addOrgParentCode").val();
								}								
							}
						}
					},
					addOrgAreaBelong:{
						"required":true
					},
					addOrgConnPerson:{
						"required":true
					},
					addOrgConnTelephone:{
						"required":true,
						"digits":true
					},
					addOrgAddress:{
						"required":true
					},
				},
				messages:{
					addOrgCode:{
						"remote":"机构编码已经存在"
					},
					addOrgName:{
						"remote":"机构名称已经存在"
					}
				},
				submitHandler:function(form){	
					$.ajax({
						url:adminQueryUrl + orgService + addMethod,
						type:'post',
						dataType:'JSON',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						headers:{'token':token,'userId':userId},
						data:$(form).serialize(),
						success:function(data){
							
							if (data.success == '1') {
			                	new $.zui.Messager('添加成功!', {
			    				    type: 'success',
			    				    placement:'center'
			    				}).show();
			                	$('#addModal').modal('hide', 'fit');
			                	queryListFun();
			                }
			                else{
			                	new $.zui.Messager(data.msg, {
			    				    type: 'warning',
			    				    placement:'center'
			    				}).show();
			                }
						},
						error:function(e){
							new $.zui.Messager('系统繁忙,请稍候再试!', {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
						}
					});
				}
			});
	});
	
	//修改页面初始化
	$("#updateBtn").click(function(){
		// 获取数据表格实例
		var orgListDataGrid = $('#orgListDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = orgListDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#updateForm")[0].reset();
			var url = adminQueryUrl + orgService + initUpdateMethod;
			var param = 'orgId='+selectedItems[0].Org_ID;//请求到列表页面
			console.log("url="+adminQueryUrl + orgService);
			console.log('param'+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",+userId);
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#updateModal').modal('show', 'fit');
						$.each(data.orgList, function(i, item){   
							if (data.orgInfo.orgParentCode == item.Org_Code){
								$("#updateOrgParentCode").append("<option value='"+item.Org_Code+"' selected='selected'>"+item.Org_Name+"</option>");
							}
							else {
								$("#updateOrgParentCode").append("<option value='"+item.Org_Code+"'>"+item.Org_Name+"</option>");
							}
						});  
						$("#updateOrgId").val(data.orgInfo.orgId)
						$("#updateOrgCode").val(data.orgInfo.orgCode);
						$("#updateOrgName").val(data.orgInfo.orgName);
						$("#updateOrgAreaBelong").val(data.orgInfo.areaCode);
						$("#updateOrgConnPerson").val(data.orgInfo.contactor);
						$("#updateOrgConnTelephone").val(data.orgInfo.mobile);
						$("#updateOrgAddress").val(data.orgInfo.address);
						$("#updateOrgParentCode").val(data.orgInfo.orgParentCode);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	
	//机构修改保存
	$("#updateSaveBtn").click(function(){			
		var validOrgCodeUrl = adminQueryUrl + orgService + validOrgCode ;
		var validOrgNameUrl = adminQueryUrl + orgService + validOrgName;
		$("#updateForm").validate({
			rules:{
				updateOrgCode:{
					"required":true,
					"remote":{
						url:validOrgCodeUrl,
						type:'get',
						dataType:'json',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						headers:{'token':token,'userId':userId},
						data:{
							'orgCode':function(){
								return $("#updateOrgCode").val();
							},
							'excludeOrgId':function(){
								return $("#updateOrgId").val();
							}
						}
					}
				},
				updateOrgName:{
					"required":true,
					"remote":{
						url:validOrgNameUrl,
						type:'get',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						headers:{'token':token,'userId':userId},
						dataType:'json',
						data:{
							'orgName':function(){
								return $("#updateOrgName").val();
							},
							'orgParentCode':function(){
								return $("#updateOrgParentCode").val();
							},
							'excludeOrgId':function(){
								return $("#updateOrgId").val();
							}
						}
					}
				},
				updateOrgAreaBelong:{
					"required":true
				},
				updateOrgConnPerson:{
					"required":true
				},
				updateOrgConnTelephone:{
					"required":true,
					"digits":true
				},
				updateOrgAddress:{
					"required":true
				},
			},
			messages:{
				updateOrgCode:{
					"remote":"机构编码已经存在"
				},
				updateOrgName:{
					"remote":"机构名称名称已经存在"
				}
			},
			submitHandler:function(form){
				//form.submit();
				
				$.ajax({
					url:adminQueryUrl + orgService + updateMethod,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",userId);
					},
					headers:{'token':token,'userId':userId},
					data:$(form).serialize(),
					success:function(data){
						if (data.success == '1') {
		                	new $.zui.Messager('修改成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	$('#updateModal').modal('hide', 'fit');
		                	queryListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	
	//删除机构
	$("#deleteBtn").click(function(){
		// 获取数据表格实例
		var orgListDataGrid = $('#orgListDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = orgListDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}else if(selectedItems.length >1){
			new $.zui.Messager('只能选择一条记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}else {			
				var url = adminQueryUrl + orgService + deleteMethod;
				var param = 'orgId='+selectedItems[0].Org_ID;//请求到列表页面
				$.ajax({
					url:url,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",+userId);
					},
					headers:{'token':token,'userId':userId},
					data:param,
					success:function(data){
						console.log('data='+data);
						if (data.success=='1'){
							new $.zui.Messager('删除机构成功!', {
							    type: 'success',
							    placement:'center'
							}).show();
							queryListFun();
						}else{
							new $.zui.Messager('系统繁忙,删除机构失败!', {
							    type: 'warning',
							    placement:'center'
							}).show();
						}
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
						    type: 'warning',
						    placement:'center'
						}).show();
					}
				});			
		}			
	});
	//详情页面
	$("#detailBtn").click(function(){
		// 获取数据表格实例
		var orgListDataGrid = $('#orgListDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = orgListDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}else {
			$("#detailForm")[0].reset();
			var url = adminQueryUrl + orgService + initUpdateMethod;
			var param = 'orgId='+selectedItems[0].Org_ID;//请求到列表页面
			console.log("url="+adminQueryUrl + orgService);
			console.log('param'+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",+userId);
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#detailModal').modal('show', 'fit');
						$.each(data.orgList, function(i, item){ 
							if (data.orgInfo.orgParentCode == item.Org_Code){
								$("#detailOrgParentName").val(item.Org_Name);
							}							
						});  
						$("#detailOrgId").val(data.orgInfo.orgId)
						$("#detailOrgCode").val(data.orgInfo.orgCode);
						$("#detailOrgName").val(data.orgInfo.orgName);
						$("#detailOrgAreaBelong").val(data.orgInfo.areaCode);
						$("#detailOrgConnPerson").val(data.orgInfo.contactor);
						$("#detailOrgConnTelephone").val(data.orgInfo.mobile);
						$("#detailOrgAddress").val(data.orgInfo.address);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
});